//SA omp
//$Id: sa_omp.h 709 2012-05-28 15:13:33Z Oleg.Bulychov@gmail.com $
#pragma once

#include "src/heo/include/easy_omp.h"
#include "src/heo/include/ring_coop.h"
#include "src/heo/include/xml_file.h"
#include "sa_common.h"

//__________________________________________________________________________________
/**
The Multistart Model with Ring Cooperation
*/
template<class T>
class SA_OMP:
    public SA<T>
{
public:
    typedef typename SA<T>::TEnvironment TEnvironment;
    typedef typename SA<T>::TSolution TSolution;

    typedef typename SA<T>::TDirection TDirection;
    typedef typename SA<T>::TCostType  TCostType;

    typedef typename TEnvironment::TSolution TInOutSolution;
    typedef typename TEnvironment::TStatistics TStatistics;
protected:
    //TODO move to template arg?
    ring_cooperation<omp::recv, omp::send, omp::isend> coop_;

    struct Shared
    {
        volatile int stop_;
    };

public:
    void solve(Solution_Pool<TInOutSolution>& pool, TStatistics& stat)
    {
        int np = omp_get_max_threads();
        if (1 == np)
        {//:don't bother omp
            SA<T>::solve(pool, stat);
            return;
        }
        Shared shared = {};
        omp::solver_fork< Solution_Pool<TInOutSolution>, TStatistics,
            SA_OMP<T> > f(pool, stat, *this);
        omp::communicator::run(np, f, shared);
    }

    template<class V>
    void accept(V& v)
    {
        v(static_cast<SA<T>&>(*this), "/");
        v(VAR_(coop));
    }

    void solve_OMP(Solution_Pool<TInOutSolution>& pool,
        TStatistics& stat,
        omp::communicator& comm,
        Shared& shared)
    {
        ASSERT_(this->rank_ == comm.rank());
        int np   = comm.size();
        int prev = (np + this->rank_ - 1) % np;
        int next = (this->rank_ + 1)      % np;

        this->init_From_Pool(pool);
        if (this->coop_.is_Async_Mode())
            this->init_Async_Buffer();
        this->set_Initial_Temperature();
        this->calc_Max_Step();
        this->show_Progress(0);
        stat.update(0, this->rank_, *this, this->env_);
        for (int step = 1; step <= this->max_step_; ++step)
        {
            if (this->coop_.cooperate(*this, this->rank_, prev, next, np, step,
                comm))
            {
                if (this->coop_.is_Async_Mode())
                {
                    if (this->sent_stop_)
                        break;
                }
                else
                {
                    if (shared.stop_)
                        break;
                }
            }
            else
            {
                this->move();
            }

            if (this->is_Acceptable_Solution())
            {
                this->accept_Solution();
                this->show_Progress(step);
                if (this->keep_best_)
                    this->update_Best_Solution();
            }

            if (this->stop(step))
            {
                if (1 == np || !this->coop_.get_Rate())
                    break;//:no coop - no need for 'pending stop'
                this->pending_stop_ = 1;
                shared.stop_ = 1;
            }

            this->update_Temperature(step);
            stat.update(step, this->rank_, *this, this->env_);
        }

        this->clear_OMP(comm);

        update_Pool(pool, comm, np);
    }

private:
    void update_Pool(Solution_Pool<TInOutSolution>& pool, omp::communicator& comm, int np)
    {
        if (0 == this->rank_)
        {
            pool.sol_list_.resize(np);
        }
        comm.barrier();

        TSolution const& final_sol = this->get_Final_Solution();
        //:final_sol --> pool

        TInOutSolution& it = pool.sol_list_[this->rank_];
        it.init(this->env_, this->rnd_);
        it.assign(final_sol);

        if (this->get_Debug_Level())
        {
#pragma omp critical(debug_output)
            {
                std::cout << lf 
                          << this->rank_ << ": final cost = " << final_sol.get_Cost() << lf;
            }
        }

        comm.barrier();
    }

    void clear_OMP(omp::communicator& comm)
    {
        comm.barrier();
        if (!coop_.is_Async_Mode())
            return;
        comm.clear_Data();
        comm.barrier();
    }
};
//__________________________________________________________________________________
//__________________________________________________________________________________

//EOF!
